
function validtraj = filterNoisyWidefieldTrajectories_v1_0(traj,prestimframes)

%% filtering out bad trajectories:
%set some thresholds for quality:
maxNormalizedRange = [.7,2.5];
maxNan = .25;
maxMovingStd = .3;
movingstdlength = 6;
movingstdprctile = 90;
numtrials = length(traj);
%% calculate normalized trajectory:
temp = zeros(size(traj(1).vesselTotalInten,1),size(traj(1).vesselTotalInten,2),numtrials);
for n = 1:numtrials
    temp(:,:,n) = traj(n).vesselTotalInten;
end
bl = median(temp(:,prestimframes,:),2,'omitnan');
y = temp./repmat(bl,1,size(temp,2),1);


%% loop through each trajectory and determine if it's valid
validtraj = false(length(traj),size(traj(1).maxInten,1));
for n = 1:length(traj)
    for n2 = 1:size(traj(n).vesselTotalInten,1)
        cur = y(n2,2:end,n);
        if sum(isnan(cur))>(maxNan*length(cur))
            validtraj(n,n2) = false;
        elseif max(cur) > maxNormalizedRange(2)
            validtraj(n,n2) = false;
        else
            temp = movstd(cur,movingstdlength,'omitnan');
            if prctile(temp,movingstdprctile) < maxMovingStd
                validtraj(n,n2) = true;
            end
        end
    end
end
